import { reactive } from "vue";
import { useUserStore } from "~/store/modulers/user";
import { ElMessage } from "element-plus";
import router from "~/router";
import { useMenuStore } from "~/store/modulers/menu";
import { storeToRefs } from "pinia";
import { getUserCompany, getUserMenu } from "~/api/system/user";
import { BaseApi } from "~/api/util/BaseService";

const userStore = useUserStore();
const menuStore = useMenuStore();
let { defaultActive } = storeToRefs(menuStore);

export class LoginApi extends BaseApi<any> {

  baseUrl = "";

  img = reactive({
    path: undefined,
    loading: false,
  });

  submitButton = reactive({
    loading: false,
    disable: false,
  });

  form = reactive<{
    loginType: string,
    accountType: "ACCOUNT" | "PHONE" | "EMAIL",
    username: string,
    password: string,
    captcha: undefined,
    uuid: undefined,
  }>({
    loginType: "system",
    accountType: "ACCOUNT",
    username: "",
    password: "",
    captcha: undefined,
    uuid: undefined,
  });

  settingState = reactive({
    code: false,
    copyright: false,
    copyrightLinkUrl: false,
    doubleAuth: false,
    smsCode: false,
    title: false,
  });

  smsState = reactive({
    loading: false,
    msg: "发送短信验证码",
    timing: 60,
  });

  constructor() {
    super();
    this.loginSetting();
  }

  sendMail() {
    if (!this.form.username || this.form.username.length == 0) {
      ElMessage.error("请输入邮箱");
      return false;
    }
    this.http.get("/auth/sendMail", { params: { email: this.form.username } }).then(res => {
      if (res.ok) {
        ElMessage.success("发送成功，请在邮箱中查看验证码");
      }
    });
  }

  sendSmsCode() {
    if (this.smsState.timing != 60) {
      return false;
    }
    if (!this.form.username || this.form.username.length == 0) {
      ElMessage.error("请输入手机号");
      return false;
    }
    this.smsState.loading = true;
    this.http.get("/auth/sendSmsCode", { params: { phone: this.form.username } }).then(res => {
      if (res.ok) {
        ElMessage.success("发送成功，请注意查看手机短信");
        setTime();
      }
    }).finally(() => {
      this.smsState.loading = false;
    });

    const _this = this;

    function setTime() {
      if (_this.smsState.timing === 0) {
        _this.smsState.timing = 60;
        _this.smsState.msg = "发送短信验证码";
      } else {
        _this.smsState.timing--;
        _this.smsState.msg = `${_this.smsState.timing}s 后可重新发送`;
        setTimeout(function() {
          setTime();
        }, 1000);
      }
    }
  }

  changLoginType(type: "ACCOUNT" | "PHONE" | "EMAIL") {
    this.form.accountType = type;
    this.form.username = "";
    this.form.password = "";
  }

  loginSetting() {
    this.http.get("/auth/loginSetting").then(res => {
      this.settingState.code = res.data.code;
    });
  }

  login() {
    if (this.form.accountType == "ACCOUNT") {
      this.loginByUsername();
    }
    if (this.form.accountType == "PHONE") {
      this.loginByPhone();
    }
    if (this.form.accountType == "EMAIL") {
      this.loginByEmail();
    }
  }

  loginByUsername() {
    this.submitButton.loading = true;
    this.safeRequest("/auth/login", this.form).then(res => {
      this.afterLogin(res);
    }).catch(() => {
      this.captchaImage();
    }).finally(() => {
      this.submitButton.loading = false;
    });
  }
  loginByPhone() {
    this.submitButton.loading = true;
    this.safeRequest("/auth/loginByPhone", {
      phone: this.form.username,
      code: this.form.password,
    }).then(res => {
      this.afterLogin(res);
    }).catch(() => {
      this.captchaImage();
    }).finally(() => {
      this.submitButton.loading = false;
    });

  }

  loginByEmail() {
    this.submitButton.loading = true;
    this.safeRequest("/auth/loginByEmail", {
      phone: this.form.username,
      code: this.form.password,
    }).then(res => {
      this.afterLogin(res);
    }).catch(() => {
      this.captchaImage();
    }).finally(() => {
      this.submitButton.loading = false;
    });
  }

  afterLogin(res: any) {
    if (res.ok) {

      this.submitButton.disable = true;
      userStore.setUserInfo(res.data as any);
      ElMessage.success({
        message: "登录成功",
      });
      getUserCompany().then(res => {
        if (res.data) {
          userStore.setCompany(res.data);
        }
      });
      getUserMenu().then(res => {
        if (res.data) {
          menuStore.refreshMenu(res.data);
        }
      });
      if (defaultActive?.value) {
        router.push(defaultActive?.value);
      } else {
        menuStore.setDefaultActive("/home");
        router.push("/home");
      }
    }

  }

  captchaImage() {
    const _this = this;
    _this.img.loading = true;
    const url: string = "/auth/captchaImage";
    this.http.get(url).then((res: any) => {
      _this.img.loading = false;
      _this.form.uuid = res.data.uuid;
      _this.img.path = res.data.img;
    });
  }
}
